<?php
error_reporting(0);

// 缓存配置
define("CACHE_DIR", __DIR__ . "/cacheHD/");
define("CACHE_TIMEOUT", 10800);
define("MAX_CACHE_FILES", 1000);

// 创建安全的缓存目录
if (!file_exists(CACHE_DIR)) {
    mkdir(CACHE_DIR, 0777, true);
}

header('Content-Type: application/json');
$n = [
    'CCTV1' => '608807420', //CCTV1综合
    'CCTV2' => '631780532', //CCTV2财经
    'CCTV3' => '624878271', //CCTV3综艺
    'CCTV4' => '631780421', //CCTV4中文国际
    'CCTV5' => '641886683', //CCTV5体育
    'CCTV5p' => '641886773', //CCTV5+体育赛事
    'CCTV6' => '624878396', //CCTV6电影
    'CCTV7' => '673168121', //CCTV7国防军事
    'CCTV8' => '624878356', //CCTV8电视剧
    'CCTV9' => '673168140', //CCTV9纪录
    'CCTV10' => '624878405', //CCTV10科教
    'CCTV11' => '667987558', //CCTV11戏曲
    'CCTV12' => '673168185', //CCTV12社会与法
    'CCTV13' => '608807423', //CCTV13新闻
    'CCTV14' => '624878440', //CCTV14少儿
    'CCTV15' => '673168223', //CCTV15音乐
    'CCTV17' => '673168256', //CCTV17农业农村
    "东方卫视" => '651632648', //东方卫视
    "内蒙古卫视" => '738911430', //内蒙古卫视
    "广东卫视" => '608831231', //广东卫视
    "江苏卫视" => '623899368', //江苏卫视
    "江西卫视" => '783847495', //江西卫视
    "河南卫视" => '790187291', //河南卫视
    "浙江卫视" => "783845111", //浙江卫视
    "湖北卫视" => '738906825', //湖北卫视
	"陕西卫视" => '738910838', //陕西卫视
    "CHC影迷电影" => '738921833', //CHC影迷电影
	"CHC家庭影院" => "783235131", //CHC家庭影院
    "CHC动作电影" => '732206245', //CHC动作电影
];

$id = isset($_GET['id']) ? trim($_GET['id']) : '';
if (empty($id)) {
    http_response_code(400);
    die(json_encode(['error' => '无效的频道ID']));
}

$cacheFile = CACHE_DIR . 'cache_' . md5($id) . '.json';

// 1. 尝试读取有效缓存
if (file_exists($cacheFile)) {
    $cacheData = json_decode(file_get_contents($cacheFile), true);
    if ($cacheData && (time() - $cacheData['created_at']) < CACHE_TIMEOUT) {
        deliverM3U8($cacheData['real_url']);
        exit;
    }
}

// 2. 获取最终播放地址
$finalUrl = getFinalPlayUrl($id);

// 3. 处理并缓存结果
if ($finalUrl) {
    // 缓存数据（包含过期时间校验）
    $cacheData = [
        'real_url' => $finalUrl,
        'created_at' => time(),
        'expires_at' => time() + 10800 // 预计过期时间
    ];
    file_put_contents($cacheFile, json_encode($cacheData));
    
    // 异步清理旧缓存（每10次请求清理1次）
    if (rand(1, 10) === 1) cleanCache();
    
    deliverM3U8($finalUrl);
} else {
    // 失败时尝试使用旧缓存（即使过期）
    if (!empty($cacheData['real_url'])) {
        header('X-Cache-Status: expired');
        deliverM3U8($cacheData['real_url']);
    } else {
        http_response_code(502);
        die(json_encode(['error' => '无法获取播放地址']));
    }
}

function getFinalPlayUrl($id) {
    $apiUrl = base64_decode("aHR0cDovL2FwaS5taWd1aGQubW9yZWZ1bi5jbjozMzI5LzdkMkE5ZzVDMThoLz91cHN0cmVhbT1odHRwOi8vYXBpMi5taWd1aGQuYmF6eC5jb20uY24vbGl2ZS5waHA/aWQ9") . urlencode($id);
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_NOBODY => true,          
        CURLOPT_FOLLOWLOCATION => true,  
        CURLOPT_MAXREDIRS => 5,         
        CURLOPT_TIMEOUT => 10,
        CURLOPT_USERAGENT => 'MGPlayer/1.0',
        CURLOPT_HEADER => true,         
        CURLOPT_RETURNTRANSFER => true
    ]);
    
    $response = curl_exec($ch);
    $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // 验证是否是有效的m3u8地址
    if ($httpCode == 200 && strpos($effectiveUrl, '.m3u8') !== false) {
        return $effectiveUrl;
    }
    return false;
}

/**
 * 发送M3U8流媒体头信息
 */
function deliverM3U8($url) {
    header("Content-Type: application/vnd.apple.mpegURL");
    header("Location: " . $url);
    //header("X-Accel-Redirect: " . $url);  // 适用于Nginx反向代理
    exit;
}

/**
 * 清理过期缓存
 */
function cleanCache() {
    $files = glob(CACHE_DIR . "cache_*.json");
    if (count($files) > MAX_CACHE_FILES) {
        foreach ($files as $file) {
            if (filemtime($file) < time() - CACHE_TIMEOUT) {
                @unlink($file);
            }
        }
    }
}
?>